package com.lin.Rpc;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Server {

/*
    实现RabbitMQ来实现一个rpc调用
    主要原理--给每一个消息添加一个回调队列的信息，这样rpc服务在计算出结果之后可以将结果送入对应的回调队列中，供调用者取出
 */

    private static String requestQueueName = "fibo_rpc_queue";


//    启动这一个server
    public static void work() throws IOException {
        Connection connection = RabbitUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(requestQueueName,false,false,false,null);
//        清空队列中所有的信息
        channel.queuePurge(requestQueueName);

        DeliverCallback deliverCallback = (consumerTag,delivery)->{
            AMQP.BasicProperties props = new AMQP.BasicProperties
                    .Builder()
                    .correlationId(delivery.getProperties().getCorrelationId())
                    .build();
            String response = "";

            try {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                int n = Integer.parseInt(message);
                int res = fibo(n);
                response += res;
            } catch (Exception e) {
                response = e.toString();
            } finally {
                channel.basicPublish("",delivery.getProperties().getReplyTo(),props,response.getBytes(StandardCharsets.UTF_8));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
            }
        };

        channel.basicConsume(requestQueueName,false,deliverCallback,consumerTag->{});
    }

    public static int fibo(int n) {
        if(n==0)return 0;
        if(n==1)return 1;
        return fibo(n-1) + fibo(n-2);
    }


}
